package transport;

import java.util.HashMap;
import network.*;

public class TransportLayer {

	public static String myID;
	public static TransportMessageHandler handler;
	public static HashMap<String, Acksend> hashACKsend;
	public static HashMap<String, SlidingWindow> hashSWsend;
	public static HashMap<String, SWReceive> hashSWReceive;
	public static HashMap<String, Integer> hashAckReceive;

	// Integrate ACK hashmaps elements

	public static void init(String ID, String server) {
		NetworkLayer.init(ID, server);
		myID = NetworkLayer.myID;
		hashACKsend = new HashMap<String, Acksend>();
		hashAckReceive = new HashMap<String, Integer>();
		hashSWsend = new HashMap<String, SlidingWindow>();
		hashSWReceive = new HashMap<String, SWReceive>();
		handler = new TransportMessageHandler();
		new Thread(handler).start();
	}

	public static synchronized void send(String msg, int mode) { // 0 is Best Effort, 1 is
		// ACK, 2 is
		// Sliding Window
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {

		}
		if (mode == 0) {
			// System.out.println("Transport " + msg);
			NetworkLayer.send(msg);
		} else if (mode == 1) {
			String dest = msg.split(":")[0];
			if (!hashACKsend.containsKey(dest)) {
				hashACKsend.put(dest, new Acksend(dest, msg));
			} else {
				hashACKsend.get(dest).update(msg);
			}
		} else if (mode == 2) {
			String dest = msg.split(":")[0];
			if (!hashSWsend.containsKey(dest)) {
				hashSWsend.put(dest, new SlidingWindow(dest, msg));
			} else {
				hashSWsend.get(dest).updateHashSND(msg);
			}
		}

	}

	public static void receive(String msg) {
		handler.handleMessage(msg);
	}

	public static void handleIncomingACKTransaction(String source) {
		if (!hashAckReceive.containsKey(source)) {
			hashAckReceive.put(source, 0);
			NetworkLayer.send(source + ":" + NetworkLayer.myID + ":ACK:" + 0);
		}
	}

	public static void viderACKsend(String dest) {
		hashACKsend.remove(dest);
	}

	public static void viderSWsend(String dest) {
		hashSWsend.remove(dest);
	}

	public static void viderSWreceive(String dest) {
		hashSWReceive.remove(dest);
	}

}
